<?php

namespace catchAdmin\apipatient\controller;

use app\common\business\Contract;
use app\common\lib\ZhyxMongo;
use catchAdmin\apidoctor\service\MbqyService;
use catcher\CatchResponse;
use catcher\base\CatchController;
use app\common\model\ServiceBind as ServiceBindModel;
use app\common\model\ServiceItem as ServiceItemModel;
use app\common\model\ServicePackage as ServicePackageModel;
use app\common\model\ServiceContent as ServiceContentModel;
use think\model\Collection;
use think\Request;
use catchAdmin\apipatient\validate\FwValidate;
use think\exception\ValidateException;

class Fw extends CatchController
{
    /**
     * 获取服务分类
     *
     * @time 2020年01月09日
     * @return \think\response\Json
     */
    public function get_fw_class(): \think\response\Json
    {
        return CatchResponse::paginate((new ServiceItemModel)->getFwClass());
    }

    /**
     * 获取服务分类下服务包
     *
     * @time 2020年01月09日
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_fw_pack(Request $request): \think\response\Json
    {
        $req = $request->param();

        #验证参数
        try {
            validate(FwValidate::class)->scene('get_fw_pack')->check($req);
            return CatchResponse::success((new ServiceBindModel)->getFwPack($req['item_id']));
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
    }


    /**
     * 获取服务包下服务内容
     *
     * @time 2020年01月09日
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_fw_content(Request $request): \think\response\Json
    {
        $req = $request->param();

        #验证参数
        try {
            validate(FwValidate::class)->scene('get_fw_content')->check($req);
            return CatchResponse::success((new ServicePackageModel)->getWhereId($req['item_id'], $req['pack_id']));
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
    }

    /**
     * 服务内容详情
     * @time 2020年10月27日
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_fw_content_detail(Request $request): \think\response\Json
    {
        $req = $request->param();

        #验证参数
        try {
            validate(FwValidate::class)->scene('get_fw_content_detail')->check($req);
            return CatchResponse::success((new ServiceContentModel)->getOneData($req['content_id']));
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
    }

    public function getMyServicesSigned(Request $request)
    {
        $limit = $request->param("limit", 15, "int");

        /*$result = (new Contract())->getListByPatientId($request->userInfo["patientId"], $limit);
        if (count($result->items()) > 0) {
            $result->visible(["id", "service_info", "contract_doctor", "name"])->append(["service_day"]);
        }*/

        $collection = ZhyxMongo::getInstance()->setCollection('contract');
        $cursor = $collection->aggregate([['$match' => ['patientId' => $request->userInfo["patientId"], 'deleted_at' => 0]], ['$unwind' => ['path' => '$contract_doctor', 'preserveNullAndEmptyArrays' => false]], ['$group' => ['_id' => '$contract_doctor.doctor_id', 'result' => ['$addToSet' => '$contract_doctor']]], ['$project' => ['_id' => false, 'result' => true]]]);

        $result = iterator_to_array($cursor, true);

        if (!empty($result)) {
            $result = $result[0];
            foreach ($result["result"] as $k => &$v) {
                //根据id获取医生信息
                $doctorInfo = (new \app\common\model\Contract())->getDoctorInfo($v["doctor_id"]);

                $v = array_merge((array)$v, $doctorInfo);

            }
        }

        return CatchResponse::success($result);
    }

    /**
     * 已签约服务包列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function getHzdSignedServicePack(Request $request): \think\response\Json
    {
        $req = $request->param();
        $list = (new MbqyService())->getSignedServicePack(0, $request->userInfo["patientId"],$req['status']??1);

        $contract_status_test = config('dictionary.contract_status_test');

        //把服务周期遍历到服务包中
        foreach ($list as $key => $val) {
            $list[$key]['service_info']['children'][0]['cycle'] = $val['cycle'];
            $list[$key]['service_info']['children'][0]['contract_id'] = $val['id'];
            $list[$key]['service_info']['children'][0]['status'] = $contract_status_test[$val['status']];
        }

        //拼装服务包
        $packs = [];
        foreach ($list as $key => $val) {
            $packs[] = $val['service_info']['children'][0];

        }

        //拼装最后服务包信息
        $ret = [];
        foreach ($packs as $key => $val) {
            $ret[$key]['id']    = $val['id'];
            $ret[$key]['name']  = $val['name'];
            $ret[$key]['cycle'] = $val['cycle'];
            $ret[$key]['status'] = $val['status'];
            $ret[$key]['contract_id'] = $val['contract_id'];
            $content = '';
            foreach ($val['children'] as $k1 => $v1) {
                $content .= $v1['name'].',';
            }
            $ret[$key]['content'] = rtrim($content, ',');//去掉结尾的，
        }
        return CatchResponse::success($ret);
    }

    /**
     * 已签约服务包详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function getHzdSignedServicePackDetails(Request $request): \think\response\Json
    {
        $req = $request->param();
        $ret = (new MbqyService())->getSignedServicePackDetails($req['contract_id'], $req['id']);
        return CatchResponse::success($ret);
    }
}